<template>
	<div id="jsonInfoCodeBox"></div>
</template>

<script lang="ts" setup>
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker'
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker'
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
import * as monaco from 'monaco-editor'
import { format } from 'sql-formatter'
import { nextTick, ref, onBeforeUnmount, onMounted, inject } from 'vue'

import { ElMessage } from 'element-plus'
const text = ref('')
const language = ref('json')
const editorTheme = ref('vs-dark')

// monaco.languages.register({ id: 'sql' })
// // 注册语言提供程序，以便 Monaco Editor 可以识别 SQL 语句
// monaco.languages.setMonarchTokensProvider('sql', {
// 	tokenizer: {
// 		root: [
// 			// 定义 SQL 关键字等语法
// 			[/\b(AND|OR|SELECT|FROM|WHERE)\b/, 'keyword'],
// 			[/\b\d+\b/, 'number'],
// 			[/"[^"]*"/, 'string'],
// 			[/".*?"/, 'string']
// 		]
// 	}
// })

//
// MonacoEditor start
//
onBeforeUnmount(() => {
	editor.dispose()
	console.log('editor dispose')
})

onMounted(() => {
	editorInit()
	console.log('editor init')
})

// @ts-ignore
self.MonacoEnvironment = {
	getWorker(_: string, label: string) {
		if (label === 'json') {
			return new jsonWorker()
		}
		if (label === 'css' || label === 'scss' || label === 'less') {
			return new cssWorker()
		}
		if (label === 'html' || label === 'handlebars' || label === 'razor') {
			return new htmlWorker()
		}
		if (['typescript', 'javascript'].includes(label)) {
			return new tsWorker()
		}
		return new EditorWorker()
	}
}
let editor = null
//从父组件获取当前每个tab对应的值和编辑的tab名称
// const editorValues = inject('editorValues')
// const editableTabsValue = inject('editableTabsValue')

const editorInit = () => {
	nextTick(() => {
		!editor
			? (editor = monaco.editor.create(document.getElementById('jsonInfoCodeBox') as HTMLElement, {
					value: text.value, // 编辑器初始显示文字
					language: language.value, // 语言支持自行查阅demo
					automaticLayout: true, // 自适应布局
					theme: editorTheme.value, // 官方自带三种主题vs, hc-black, or vs-dark
					foldingStrategy: 'indentation',
					renderLineHighlight: 'all', // 行亮
					selectOnLineNumbers: true, // 显示行号
					minimap: {
						enabled: false
					},
					cursorStyle: 'line', //光标样式
					readOnly: false, // 只读
					fontSize: 16, // 字体大小
					autoIndent: true, //自动布局
					useTabStops: false,
					wordWrap: 'on',
					quickSuggestionsDelay: 100, //代码提示延时
					scrollBeyondLastLine: false, // 取消代码后面一大段空白
					overviewRulerBorder: false // 不要滚动条的边框
			  }))
			: editor.setValue('{}')
		// console.log(editor)
	})
}

let sqlFormatNew = ''
const setEditorValue = (value: any) => {
	editor.setValue(value)
	if (value) {
		const model = editor.getModel()
		const text = model.getValue()
		const datajson = JSON.parse(text)
		let querySql = ''
		if (datajson.job && datajson.job.content) {
			querySql = datajson.job.content[0].reader.parameter.connection[0].querySql
			if (querySql) {
				const sqlstring = querySql[0].replace(/\\n/g, '\n')
				sqlFormatNew = ('@@' + format(sqlstring.replace(/"select[^"]*"/gi)) + '@@').replace(/\|\s*\|/g, '||')
				// .replace(/\:\s*\:/g, "::")

				datajson.job.content[0].reader.parameter.connection[0].querySql[0] = '__SQL_PLACEHOLDER__'
				editor.setValue(JSON.stringify(datajson, null, 2))
			}
		}
		setTimeout(() => {
			editor.trigger(null, 'editor.action.formatDocument')
			nextTick(() => {
				if (querySql) {
					const newValue = editor.getValue().replace('__SQL_PLACEHOLDER__', sqlFormatNew)
					editor.setValue(newValue)
					setTimeout(() => {
						editor.setValue(editor.getValue().replace(/\:\s*\:\s*/g, '::'))
					}, 200)
				}
			})
			editor.setValue(editor.getValue())
		}, 100)
	}
}

const getEditorValue = () => {
	const valueJson = editor.getValue()

	const sliptJson = valueJson.replace(/@@select.*@@/gsi, (_, value) => {
		return JSON.stringify(value)
	})

	const matches = []
	let match
	const regex = /@@\s*(.*?)@@/g
	while ((match = regex.exec(JSON.stringify(valueJson))) !== null) {
		matches.push(match[1])
	}

	const newData = JSON.parse(sliptJson)
	if (newData.job.content[0].reader.parameter.connection[0].querySql) {
		newData.job.content[0].reader.parameter.connection[0].querySql[0] = matches[0]
	} else {
	}
	return JSON.stringify(newData)
}

const sqlFormatter = (value: any) => {
	return format(value)
}

/***
 * editor.setValue(newValue)

editor.getValue()

editor.onDidChangeModelContent((val)=>{ //监听值的变化  })

editor.getAction('editor.action.formatDocument').run()    //格式化代码

editor.dispose()    //销毁实例

editor.onDidChangeOptions　　//配置改变事件

editor.onDidChangeLanguage　　//语言改变事件
 */
defineExpose({
	editorInit,
	setEditorValue,
	getEditorValue,
	sqlFormatter
})
</script>

<style scoped>
#jsonInfoCodeBox {
	width: 100%;
	height: calc(100% - 20px);
}
</style>
